#include "board.h"

/**
 * @addtogroup STM32
 */

/*@{*/

/*******************************************************************************
* Function Name  : NVIC_Configuration
* Description    : Configures Vector Table base location.
* Input          : None
* Output         : None
* Return         : None
*******************************************************************************/
void NVIC_Configuration(void)
{
  NVIC_InitTypeDef NVIC_InitStructure;   

  NVIC_InitStructure.NVIC_IRQChannel =  USART1_IRQn;  //TIM1_BRK_UP_TRG_COM_IRQn,TIM1_CC_IRQn 
  NVIC_InitStructure.NVIC_IRQChannelPriority = 1; 
  NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE; 
  NVIC_Init(&NVIC_InitStructure); 
}

/**
 * This RCC initial for system.
 * use HSI clock source and pll
 * HSI = 8; sysclk = 8/2 * 12 = 48MHZ
 * sysclk source is pllclk
 * AHB prescaler is 1, HCLK = SYSCKL = SystemCoreClock = 48MHZ
 */
static void RCC_Configuration(void)
{
    RCC_DeInit();
    
    /* Enable HSE */
    RCC_HSEConfig(RCC_HSE_ON);
    if (RCC_WaitForHSEStartUp() == SUCCESS)
    {
        /* HCLK = SYSCLK */
        RCC_HCLKConfig(RCC_SYSCLK_Div1);
        
        /* PCLCLK = RCC_HCLK_Div1 */
        RCC_PCLKConfig(RCC_HCLK_Div1);

        //RCC_USARTCLKConfig(RCC_USART1CLK_SYSCLK);
        
        /* Enable Prefetch Buffer */
        FLASH_PrefetchBufferCmd(ENABLE);
        /* Flash 2 wait state */
        FLASH_SetLatency(FLASH_Latency_0);

        /* PLLCLK = 25MHz * 2 = 50 MHz */
        RCC_PLLConfig(RCC_PLLSource_PREDIV1, RCC_PLLMul_2);
        /* Enable PLL */
        RCC_PLLCmd(ENABLE);
        /* Wait till PLL is ready */
        while (RCC_GetFlagStatus(RCC_FLAG_PLLRDY) == RESET)
        {
            ;
        }
        
        /* Select PLL as system clock source */
        RCC_SYSCLKConfig(RCC_SYSCLKSource_PLLCLK);
        /* Wait till PLL is used as system clock source */
        while (RCC_GetSYSCLKSource() != 0x08)
        {
            ;
        }
        
        /* Update SystemCoreClock value from RCC configure */
        SystemCoreClockUpdate();
    }
}


/**
 * This function will initial STM32 board.
 */
void hw_board_init(void)
{
    /* NVIC Configuration */
    NVIC_Configuration();

    /* Configure the SysTick */
    RCC_Configuration();

    /* Configure the UserTick*/
    SysTick_Config(SystemCoreClock / 100);
}

/*@}*/
